package com.example.tianwu.daydayup;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.Toast;

import com.youtu.Youtu;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Tianwu on 2015/11/19.
 */
public class PicYoutuData extends AsyncTask<Bitmap,String,String> {
    //My ID and Key
    public static final String APP_ID = "";
    public static final String SECRET_ID = "";
    public static final String SECRET_KEY = "";

    private Youtu youtu;
    private JSONObject respose;

    private Activity activity;


    public PicYoutuData(Activity activity){
        this.activity = activity;
        youtu = new Youtu(APP_ID,SECRET_ID,SECRET_KEY,Youtu.API_YOUTU_END_POINT);
    }
    @Override
    protected String doInBackground(Bitmap... bitmaps) {
        try {

            respose = youtu.DetectFace(bitmaps[0], 1);//面部分析

        }catch (Exception e){
            publishProgress(e.getMessage());
        }
        return "OK";
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //异常提示
        Toast.makeText(activity, values[0], Toast.LENGTH_LONG).show();
        ((MainActivity)activity).YoutuError();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s.equals("OK")) {
            try {
                String jsonData = respose.getString("face");
                JSONObject face = new JSONObject(jsonData.substring(1, jsonData.length() - 1));
                FaceData fd = new FaceData();
                fd.id = face.getString("face_id");
                fd.gender = face.getString("gender");
                fd.age = face.getInt("age");
                fd.expression = face.getInt("expression");
                fd.beauty = face.getInt("beauty");
                fd.glass = face.getBoolean("glass");
                ((MainActivity)activity).YoutuFinish(fd);
            } catch (JSONException je) {
                Toast.makeText(activity, je.getMessage(), Toast.LENGTH_LONG).show();
                ((MainActivity)activity).YoutuError();
            } catch (Exception e){
                Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
                ((MainActivity)activity).YoutuError();
            }
        }else {
            //nothing.
            Toast.makeText(activity, "Some Error.", Toast.LENGTH_LONG).show();
            ((MainActivity)activity).YoutuError();
        }
    }
}